package cn.qyd.threadpool;

import java.util.concurrent.*;
import java.util.stream.Stream;

/**
 * @author 邱运铎
 * @date 2024-03-14 14:31
 */
public class ThreadPoolDemo01 {
    public static void main(String[] args) {
        ExecutorService executorService = Executors.newFixedThreadPool(3);

        Callable<Integer>[] tasks = new Callable[5];

        for (int i = 0; i < tasks.length; i++) {
            final int index = i;
            tasks[i] = new Callable<Integer>() {
                @Override
                public Integer call() throws Exception {
                    TimeUnit.SECONDS.sleep(index + 1);
                    return (index + 1) * 1000;
                }
            };
        }
        Future<Integer>[] futures = new FutureTask[tasks.length];
        for (int i = 0; i < futures.length; i++) {
            futures[i] = executorService.submit(tasks[i]);
        }

        Stream.of(futures).forEach(future -> {
            int i = 1;
            try {
                System.out.println("Result of task[" + (i++) + "]: " + future.get());
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            } catch (ExecutionException e) {
                throw new RuntimeException(e);
            }
        });

        executorService.shutdown();
    }
}
